<script lang="ts" setup>
import { type HTMLAttributes } from 'vue';
import { useVModel } from '@vueuse/core';
import { cn } from '@/lib/utils';

const props = defineProps<{
	defaultValue?: string | number;
	modelValue?: string | number;
	class?: HTMLAttributes['class'];
}>();

const emits = defineEmits<{
	(e: 'update:modelValue', payload: string | number): void;
}>();

const modelValue = useVModel(props, 'modelValue', emits, {
	passive: true,
	defaultValue: props.defaultValue,
});

// 获取 input 元素的 ref
const inputRef = ref();
const focused = defineModel<boolean>('focused');
const changeFocused = (isFocused: boolean) => {
	// 确保 input 元素已经被渲染
	if (inputRef.value) {
		if (isFocused) {
			// 当 isFocused 为 true 时，聚焦 input 元素
			inputRef.value.focus();
		}
		else {
			// 当 isFocused 为 false 时，取消 input 元素的焦点
			inputRef.value.blur();
		}
	}
};

onMounted(() => {
	changeFocused(focused.value ?? false);
});

watch(focused, (isFocused) => {
	changeFocused(isFocused ?? false);
});

const handleBlur = () => {
	// 当 input 元素失去焦点时，将 isFocused 设置为 false
	focused.value = false;
};
const handleFocus = () => {
	// 当 input 元素获得焦点时，将 isFocused 设置为 true
	focused.value = true;
};
</script>

<template>
	<input
		ref="inputRef"
		v-model="modelValue"
		:class="cn('flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50', props.class)"
		@blur="handleBlur"
		@focus="handleFocus"
	>
</template>
